package leetcode.offer_two_special.string;

/**
 * @author mazouri
 * @create 2021-09-05 23:34
 */
public class _16_lengthOfLongestSubstring {
    public int lengthOfLongestSubstring1(String s) {
        if (s.length() == 0) return 0;

        char[] chars = s.toCharArray();
        // s 由英文字母、数字、符号和空格组成 ASCII码共有256
        int[] counts = new int[256];
        int j = -1;
        int maxLen = 0;

        for (int i = 0; i < chars.length; i++) {
            counts[chars[i]]++;
            while (greater1(counts)) {
                j++;
                counts[chars[j]]--;
            }

            maxLen = Math.max(maxLen, i - j);
        }

        return maxLen;
    }

    private boolean greater1(int[] counts) {
        for (int count : counts) {
            if (count > 1) return true;
        }
        return false;
    }

    public int lengthOfLongestSubstring(String s) {
        if (s.length() == 0) return 0;

        char[] chars = s.toCharArray();
        // s 由英文字母、数字、符号和空格组成 ASCII码共有256
        int[] counts = new int[256];
        int j = -1;
        int maxLen = 0;
        int countDup = 0;
        for (int i = 0; i < chars.length; i++) {
            counts[chars[i]]++;
            if (counts[chars[i]] == 2) {
                countDup++;
            }

            while (countDup > 0) {
                j++;
                counts[chars[j]]--;
                if (counts[chars[j]] == 1) countDup--;
            }

            maxLen = Math.max(maxLen, i - j);
        }
        return maxLen;
    }

    public static void main(String[] args) {
        System.out.println(new _16_lengthOfLongestSubstring().lengthOfLongestSubstring("babcca"));
    }
}
